package com.itheima.es.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.es.entity.Result;
import com.itheima.es.pojo.Sku;
import com.itheima.es.service.SkuService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController("good")
public class SkuController {
    @Autowired
    private SkuService skuService;
    private RestHighLevelClient  client;
    /**
     * 分页查询
     * @param
     * @return
     */
    @GetMapping("findPage/{page}/{size}")
    public void findPage(@PathVariable("page")int page ,@PathVariable("size")int size)
            throws IOException {

          client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.200.150",9200,"http")));

        //1. 从数据库查询文档数据,先写死数据
        int currentPage = 1;
        int pageSize = 10000;

        while (true) {
            List<Sku> sukList = skuService.findPage(currentPage,pageSize);
            //判断是否查询完
            if(sukList.size()<=0){
                return;
            }
            //2. 创建BulkRequest对象
            BulkRequest bulkRequest = new BulkRequest();
            //3. 创建多个IndexRequest对象，组织文档数据，并添加到BulkRequest中
            for (Sku sku : sukList) {
                bulkRequest.add(new IndexRequest("sku").
                        id(String.valueOf(sku.getId())).
                        source(JSON.toJSONString(sku), XContentType.JSON));
            }
            //每次插入10000条数据
            //4. 发起请求
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println("已经成功插入"+sukList.size()+"条数据");
            currentPage++;
            client.close();
        }
    }




}
